#include "mnetworktask.h"

#include <QThread>
#include <QDebug>
#include <QHostAddress>


mNetworkTask::mNetworkTask(QObject *parent) : QObject(parent)
{

}


NetworkTask_01::NetworkTask_01(QObject *parent) : QObject(parent)
{

}

void NetworkTask_01::Task01(QString rmtIP, unsigned short rmtPort)
{
    qDebug() << "当前 NetworkTask_01 线程对象的地址: " << QThread::currentThread();

    qDebug() << " NetworkTask_01 " << rmtIP << ":" << rmtPort ;


    m_tcp = new QTcpSocket(this);
    m_tcp->bind(QHostAddress::Any,6666);//固定本机端口
    m_tcp->connectToHost(QHostAddress(rmtIP), rmtPort);
    connect(m_tcp, &QTcpSocket::readyRead, [=]()
    {
        // 接收服务器发送的数据
        QByteArray recvMsg = m_tcp->readAll();
        qDebug() << recvMsg;

        emit task_recv_msg(recvMsg);

    });

    // 检测是否和服务器是否连接成功了
    connect(m_tcp, &QTcpSocket::connected, this, [=]()
    {
        //发送信号:成功连接仪器 emit myTask1_connectInstrOK();
    });

    // 检测服务器是否和客户端断开了连接
    connect(m_tcp, &QTcpSocket::disconnected, this, [=]()
    {
        //断开，销毁
        m_tcp->close();
        m_tcp->deleteLater();
    });

}

void NetworkTask_01::recv_disconncet()
{
    m_tcp->close();
    m_tcp->deleteLater();
}

void NetworkTask_01::recv_query()
{
    QString cmd = "*IDN?\r\n";
    m_tcp->write(cmd.toUtf8());
}

NetworkTask_02::NetworkTask_02(QObject *parent)
{

}

void NetworkTask_02::Task02(QString rmtIP, unsigned short rmtPort)
{
    qDebug() << "当前 NetworkTask_02 线程对象的地址: " << QThread::currentThread();
    qDebug() << " NetworkTask_02 " << rmtIP << ":" << rmtPort ;


    m_tcp = new QTcpSocket(this);
    m_tcp->bind(QHostAddress::Any,6667);//固定本机端口
    m_tcp->connectToHost(QHostAddress(rmtIP), rmtPort);
    connect(m_tcp, &QTcpSocket::readyRead, [=]()
    {
        // 接收服务器发送的数据
        QByteArray recvMsg = m_tcp->readAll();
        qDebug() << recvMsg;
        emit task_recv_msg(recvMsg);

    });

    // 检测是否和服务器是否连接成功了
    connect(m_tcp, &QTcpSocket::connected, this, [=]()
    {
        //发送信号:成功连接仪器
    });

    // 检测服务器是否和客户端断开了连接
    connect(m_tcp, &QTcpSocket::disconnected, this, [=]()
    {
        //断开，销毁
        m_tcp->close();
        m_tcp->deleteLater();
    });

}

void NetworkTask_02::recv_disconncet()
{
    m_tcp->close();
    m_tcp->deleteLater();
}

void NetworkTask_02::recv_query()
{
    QString cmd = "*IDN?\r\n";
    m_tcp->write(cmd.toUtf8());
}

